const { default: axios } = require("axios");
const qs = require("qs");
const Ret = require("./ret");

module.exports = class Service {
  static #domain;
  static #isTest;
  static #stage;
  static #urlPrefix;

  static init(domain, isTest = true, isStage = false) {
    this.#domain = domain;
    this.#isTest = isTest;
    this.#stage = isStage;
    this.#urlPrefix =
      "http://SERVICE." +
      (isStage ? "stage" : isTest ? "test" : "prod") +
      "." +
      domain;
  }

  static setDelay(async = false, asyncDelaySecond = 0) {
    let headers = {};
    if (async) {
      headers["X-Fc-Invocation-Type"] = "Async";
    }
    if (asyncDelaySecond > 0) {
      headers["x-fc-async-delay"] = asyncDelaySecond;
    }
    headers["Content-Type"] = "application/x-www-form-urlencoded";
    return headers;
  }

  static async get(
    serviceName,
    path,
    params,
    async = false,
    asyncDelaySecond = 0
  ) {
    let url = this.#urlPrefix.replace("SERVICE", serviceName) + path;
    try {
      if (params) {
        url += "?" + qs.stringify(params);
      }
      const headers = this.setDelay(async, asyncDelaySecond);
      const result = await axios.get(url, { headers });
      return result.data;
    } catch (e) {
      console.error("获取失败", url, e.message);
      return new Ret(false, "获取失败", Ret.CODE_SYSTEM);
    }
  }

  static async post(
    serviceName,
    path,
    params = {},
    async = false,
    asyncDelaySecond = 0,
    formFormat = true
  ) {
    let url = this.#urlPrefix.replace("SERVICE", serviceName) + path;
    try {
      let headers = this.setDelay(async, asyncDelaySecond);
      if (!formFormat) {
        headers["Content-Type"] = "application/json";
      }
      const result = await axios.post(
        url,
        formFormat ? qs.stringify(params) : params,
        {
          headers,
        }
      );
      return result.data;
    } catch (e) {
      console.error("获取失败", url, e.message, e.data);
      return new Ret(false, "获取失败", Ret.CODE_SYSTEM);
    }
  }
};
